/**
 * This file is part of Wasagent.
 *
 * Wasagent is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Wasagent is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Wasagent. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package net.wait4it.wasagent.jmx;

import java.util.Map;
import java.util.Set;

import javax.management.ObjectName;

import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.pmi.stat.WSStats;

/**
 * @author Yann Lambret
 *
 */
public class JmxService {

	public static AdminClient getClient(Map<String,String> params) throws Exception {
		return JmxClientFactory.getInstance(params);
	}

    /*
     *
     * http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/topic/com.ibm.websphere.javadoc.doc/public_html/mbeandocs/Perf.html
     *
     * Management interface for the Performance Monitoring Infrastructure (PMI) subsystem. WebSphere Performance Monitoring Infrastructure 
     * (PMI) maintains the Stats from various components in a tree structure. Perf MBean operations can be targeted towards (a) a given 
     * element in the PMI tree -- when the recursive parameter is false (b) a given element in the PMI tree and all its children (and their 
     * children, and so on) -- when the recursive parameter is true.
     *
     */
	@SuppressWarnings("unchecked")
	public static ObjectName getPerfMbean(AdminClient client) throws Exception {
		Set<ObjectName> mbeans = client.queryNames(new ObjectName("WebSphere:*,type=Perf"), null);
		return mbeans.iterator().next();
	}

	@SuppressWarnings("unchecked")
	public static Set<ObjectName> getMbeans(AdminClient client, String query) throws Exception {
		return client.queryNames(new ObjectName(query), null);
	}

	public static ObjectName getMbean(AdminClient client, String query) throws Exception {
		Set<ObjectName> mbeans = getMbeans(client, query);
		return mbeans.iterator().next();
	}

	public static WSStats getStats(AdminClient client, ObjectName perfMbean, ObjectName mbean) throws Exception {
		String[] signature = new String[] {"javax.management.ObjectName", "java.lang.Boolean"};
		Object[] params = new Object[] {mbean, new Boolean(true)};
		return (WSStats)client.invoke(perfMbean, "getStatsObject", params, signature);
	}

}
